package com.wg.msshopcar.controller;

import com.wg.msshopcar.entity.ShopCar;
import com.wg.msshopcar.entity.dto.AddShopCarDTO;
import com.wg.msshopcar.entity.dto.CheckoutPackageDTO;
import com.wg.msshopcar.entity.dto.ShopCarDTO;
import com.wg.msshopcar.service.ShopCarService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "ShopCarController", description = "购物车控制器")
@RestController
@RequestMapping("/shopCar")
@CrossOrigin(origins = "http://localhost:5173")
public class ShopCarController {

    @Autowired
    private ShopCarService shopCarService;

    @Operation(summary = "添加购物车")
    @PostMapping
    @Parameter(name = "shopCar", description = "购物车信息对象")
    public int doAddShopCar(@RequestBody ShopCar shopCar) {
        return shopCarService.addShopCar(convertToDTO(shopCar));
    }

    // 将ShopCar对象转换为AddShopCarDTO对象的辅助方法
    private AddShopCarDTO convertToDTO(ShopCar shopCar) {
        AddShopCarDTO dto = new AddShopCarDTO();
        dto.setUserId(shopCar.getUserId());
        dto.setProductId(shopCar.getProductId());
        dto.setSku(shopCar.getSku());
        dto.setCount(shopCar.getCount());
        dto.setPrice(shopCar.getPrice());
        dto.setShopId(shopCar.getShopId());
        dto.setTime(shopCar.getTime());
        return dto;
    }

    @Operation(summary = "添加购物车（使用DTO）")
    @PostMapping("/add")
    @Parameter(name = "addShopCarDTO", description = "添加购物车参数对象")
    public ResponseEntity<Map<String, Object>> doAddShopCarWithDTO(@RequestBody AddShopCarDTO dto) {
        int result = shopCarService.addShopCar(dto); // 直接用DTO方法
        Map<String, Object> response = new HashMap<>();
        if (result > 0) {
            response.put("code", 200);
            response.put("msg", "添加成功");
        } else {
            response.put("code", 500);
            response.put("msg", "添加失败");
        }
        return ResponseEntity.ok(response);
    }

    @Operation(summary = "删除购物车")
    @DeleteMapping("/{id}")
    @Parameter(name = "id", description = "购物车编号")
    public boolean doDeleteShopCar(@PathVariable("id") String id) {
        return shopCarService.deleteShopCar(Integer.parseInt(id));
    }

    @Operation(summary = "更新购物车")
    @PutMapping
    @Parameter(name = "shopCar", description = "购物车信息对象")
    public int doUpdateShopCar(@RequestBody ShopCar shopCar) {
        return shopCarService.updateShopCar(shopCar) ? 1 : 0;
    }

    @Operation(summary = "获取所有购物车记录")
    @GetMapping
    public List<ShopCar> doGetAllShopCars() {
        return shopCarService.getAllShopCars();
    }

    @Operation(summary = "根据用户ID获取购物车列表")
    @GetMapping("/user/{userId}")
    @Parameter(name = "userId", description = "用户ID", required = true)
    public List<ShopCar> doGetShopCarsByUserId(
            @PathVariable("userId") Integer userId) {
        return shopCarService.getShopCarsByUserId(userId);
    }

    // =======================================

    /**
     * 获取购物车详情（带商品、店铺、规格信息）
     */
    @Operation(summary = "获取购物车详情（带商品、店铺、规格信息）")
    @GetMapping("/details/{userId}")
    @Parameter(name = "userId", description = "用户ID", required = true)
    public ResponseEntity<Map<String, Object>> getCartDetails(
            @PathVariable("userId") Integer userId) {
        List<ShopCarDTO> cartDetails = shopCarService.getCartDetailsByUserId(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "成功");
        response.put("data", cartDetails);
        return ResponseEntity.ok(response);
    }

    /**
     * 批量删除购物车项
     */
    @Operation(summary = "批量删除购物车项")
    @DeleteMapping("/batch")
    @Parameter(name = "cartIds", description = "购物车ID列表", required = true)
    public ResponseEntity<Map<String, Object>> batchDeleteCartItems(@RequestBody List<Integer> cartIds) {
        boolean success = shopCarService.batchDeleteCartItems(cartIds);
        Map<String, Object> response = new HashMap<>();
        if (success) {
            response.put("code", 200);
            response.put("msg", "批量删除成功");
        } else {
            response.put("code", 500);
            response.put("msg", "批量删除失败");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 结算购物车商品
     */
    @Operation(summary = "结算购物车商品")
    @PostMapping("/checkout")
    @Parameter(name = "cartIds", description = "购物车ID列表", required = true)
    public ResponseEntity<Map<String, Object>> checkoutCartItems(@RequestBody List<Integer> cartIds) {
        try {
            // 获取封装好的结算数据
            CheckoutPackageDTO checkoutPackage = shopCarService.checkoutCartItems(cartIds);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "结算数据准备成功");
            response.put("data", checkoutPackage);

            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("msg", e.getMessage());

            return ResponseEntity.ok(response);
        }
    }

}